<?php

namespace App\Http\Controllers\Api\Admin;

use App\Comment;
use App\ExpertLabel;
use App\ExpertQualificationImg;
use App\Experts;
use App\Group;
use App\GroupXUser;
use App\Http\Services\CommonManager;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Industries;
use App\PersonalAuth;
use App\SysSetUp;
use App\UnitAuth;
use App\UnitBindVipPackage;
use App\Units;
use App\User;
use App\UserAuth;
use App\UserInfo;
use App\UserXUnit;
use App\VipInfo;
use App\VipPackage;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class UserController extends Controller
{
    /**
     * 获取用户类型筛选列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserAuthTypeFilterList(Request $request){
        $DATA = [
            (object)[
                'name' => '个人认证',
                'value' => 'personal_auth',
            ],
            (object)[
                'name' => '单位认证',
                'value' => 'unit_auth',
            ],
            (object)[
                'name' => '会员单位用户',
                'value' => 'member_unit_user',
            ],
            (object)[
                'name' => 'vip用户',
                'value' => 'vip_user',
            ],
            (object)[
                'name' => '专家',
                'value' => 'expert',
            ],
        ];

        return response()->json(['level' => 'success','message' => '获取成功','data' => $DATA]);
    }

    /**
     * 后台用户列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserList(Request $request){
        $page            = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit           = !is_null($request->get('limit'))? $request->get('limit'): 10;
        $keyword         = !is_null($request->get('keyword')) ? $request->get('keyword') : '';
        $personalAuth    = !is_null($request->get('personal_auth')) ? $request->get('personal_auth') : 0;
        $unitAuth        = !is_null($request->get('unit_auth')) ? $request->get('unit_auth') : 0;
        $memberUnitUser  = !is_null($request->get('member_unit_user')) ? $request->get('member_unit_user') : 0;
        $vipUser         = !is_null($request->get('vip_user')) ? $request->get('vip_user') : 0;
        $expert          = !is_null($request->get('expert')) ? $request->get('expert') : 0;

        $pageInfo=[
            'page'  =>$page,
            'limit' =>$limit,
            'keyword' => $keyword,
            'personal_auth' => $personalAuth,
            'unit_auth' => $unitAuth,
            'member_unit_user' => $memberUnitUser,
            'vip_user' => $vipUser
        ];

        $users = User::whereRole(0);

        if ($keyword != ''){
            $nickname   =UserInfo::where('nickname','like','%'.trim($keyword).'%')->orWhere('realname','like','%'.trim($keyword).'%')->pluck('user_id')->toArray();
            $users->whereIn('id',$nickname)->orWhere('phone','like','%'.trim($keyword).'%');
        }

        $dataUserIds = [];
        if($personalAuth == 1){
            $personalAuthUserIds = PersonalAuth::whereIsAuth(1)->get();
            if(count($personalAuthUserIds) > 0){
                foreach($personalAuthUserIds as $personalAuthUserId){
                    array_push($dataUserIds,$personalAuthUserId->user_id);
                }
            }
        }

        if($unitAuth == 1){
            $unitAuthUserIds = UnitAuth::whereIsAuth(1)->get();
            if(count($unitAuthUserIds) > 0){
                foreach($unitAuthUserIds as $unitAuthUserId){
                    array_push($dataUserIds,$unitAuthUserId->user_id);
                }
            }
        }

        if($memberUnitUser == 1){
            $memberUnitIds = Units::whereIsMemberUnit(1)->pluck('id');

            $unitXUser = UserXUnit::whereIn('unit_id',$memberUnitIds)->pluck('user_id');

            /** @var UnitAuth $memberUnitUserId */
            $memberUnitUserIds = UnitAuth::whereIn('user_id',$unitXUser)->whereIsAuth(1)->get();
            if(count($memberUnitUserIds) > 0){
                foreach($memberUnitUserIds as $memberUnitUserId){
                    array_push($dataUserIds,$memberUnitUserId->user_id);
                }
            }
        }

        if($vipUser == 1){
            $userWhetherVipOne = VipInfo::whereStatus(1)->where('end_time','>',date('Y-m-d H:i:s',time()))->get();
            if(count($userWhetherVipOne) > 0){
                foreach($userWhetherVipOne as $val){
                    array_push($dataUserIds,$val->user_id);
                }
            }

            $vipUnitIds = UnitBindVipPackage::where('end_time','>',date('Y-m-d H:i:s',time()))->pluck('unit_id')->toArray();

            $vipUnitUserIds = UserXUnit::whereIn('unit_id',$vipUnitIds)->pluck('user_id');

            /** @var UnitAuth $item */
            $userWhetherVipTwo = UnitAuth::whereIn('user_id',$vipUnitUserIds)->whereIsAuth(1)->get();
            if(count($userWhetherVipTwo) > 0){
                foreach($userWhetherVipTwo as $item){
                    array_push($dataUserIds,$item->user_id);
                }
            }
        }

        if($expert == 1){
            $isExpert = Experts::whereIsAuth(1)->get();
            if(count($isExpert)> 0){
                foreach ($isExpert as $expert){
                    array_push($dataUserIds,$expert->user_id);
                }
            }
        }

        array_unique($dataUserIds);

        if(count($dataUserIds) > 0){
            $users = $users->whereIn('id',$dataUserIds);
        }

        $pageInfo['total'] = $users->count();

        $users = $users->orderBy('created_at','desc')->offset(($page - 1) * $limit)->limit($limit)->get();
        if (count($users) > 0){
            /** @var User $user */
            foreach ($users as $user){
                $user->userInfo;
                if ($user->userInfo){
                    $user->userInfo->photo_url = '';
                    $user->userInfo->is_personal_auth = 0;
                    $user->userInfo->is_unit_auth = 0;
                    $user->userInfo->work_img_url = '';
                    $user->userInfo->is_expert_auth = 0;
                    $user->userInfo->is_member_unit = 0;
                    $user->userInfo->is_vip = 0;

                    $user->userInfo->vip_package_name = '';

                    $userBindVipPackageList = CommonManager::getUserBindVipPackageInfo($user->id);
                    if(count($userBindVipPackageList) > 0){
                        foreach($userBindVipPackageList as $userBindVipPackage){
                            if(!empty($userBindVipPackage->vip_package_info)){
                                $user->userInfo->vip_package_name = $userBindVipPackage->vip_package_info->name;
                            }
                            break;
                        }
                    }

                    $userInfo = CommonManager::getUserBasicInfo($user->id);
                    if($userInfo){
                        $user->userInfo->photo_url = $userInfo['photo_url'];
                        $user->userInfo->is_personal_auth = $userInfo['is_personal_auth'];
                        $user->userInfo->is_unit_auth = $userInfo['is_unit_auth'];
                        if($userInfo['is_personal_auth'] == 1){
                            $personalAuth = PersonalAuth::whereUserId($user->id)->whereIsAuth(1)->first();
                            if($personalAuth){
                                $user->userInfo->work_img_url = FileManager::getImgUrl($personalAuth->work_img_id);
                            }
                        }
                        $user->userInfo->is_expert_auth = $userInfo['is_expert_auth'];
                        $user->userInfo->is_member_unit = $userInfo['is_member_unit'];
                        $user->userInfo->is_vip = $userInfo['is_vip'];
                    }
                }
            }
        }

        return response()->json(['level'=>'success','message'=>'success','data'=>$users,'page_info'=>$pageInfo]);
    }

    /**
     * 用户详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserDetail(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        if($id == 0 || $id == ''){
            if($adminUser->role == 0){
                $id = $adminUser->id;
            }
        }

        $userInfo = UserInfo::whereUserId($id)->first();
        if($userInfo){
            $userBasicInfo = CommonManager::getUserBasicInfo($userInfo->user_id);
            $userInfo->phone = $userBasicInfo ? $userBasicInfo['phone'] : '';
            $userInfo->is_member_unit = $userBasicInfo ? $userBasicInfo['is_member_unit'] : 0;
            $userInfo->is_vip = $userBasicInfo ? $userBasicInfo['is_vip'] :0;
            $userInfo->email = $userBasicInfo ? $userBasicInfo['email'] : 0;
            $userInfo->industry = '';
            $userInfo->photo_url = $userBasicInfo ? $userBasicInfo['photo_url'] : '';
            $belongGroup = '';
            $userXGroupList = GroupXUser::whereUserId($userInfo->user_id)->get();
            if(count($userXGroupList) > 0){
                foreach($userXGroupList as $userXGroup){
                    $groupInfo = Group::whereId($userXGroup->group_id)->first();
                    if($groupInfo){
                        if($belongGroup == ''){
                            $belongGroup = $groupInfo->name;
                        }else{
                            $belongGroup = $belongGroup . ',' . $groupInfo->name;
                        }
                    }
                }
            }
            $userInfo->belong_group = $belongGroup;

            $industry = Industries::whereId($userInfo->industry_id)->first();
            if($industry) {
                $userInfo->industry = $industry->name;
            }

            $userInfo->is_personal_auth = CommonManager::isPersonalAuth($userInfo->user_id);
            $userInfo->personal_auth_info = CommonManager::getPersonalAuthInfo($userInfo->user_id);

            $userInfo->is_unit_auth = CommonManager::isUnitAuth($userInfo->user_id);
            $userInfo->unit_info = CommonManager::getUnitInfo($userInfo->user_id);

            $vipPackageList = [];

            $userBindVipPackageList = CommonManager::getUserBindVipPackageInfo($userInfo->user_id);
            if(count($userBindVipPackageList) > 0){
                foreach($userBindVipPackageList as $userBindVipPackage){
                    $vip_package_id   = 0;
                    $vip_package_name = '';
                    $vip_package_free = 0.00;
                    if(!empty($userBindVipPackage->vip_package_info)){
                        $vip_package_id   = $userBindVipPackage->vip_package_info->id;
                        $vip_package_name = $userBindVipPackage->vip_package_info->name;
                        $vip_package_free = $userBindVipPackage->vip_package_info->free;
                    }

                    $bind_method = $userBindVipPackage->bind_method;
                    $bind_method_name = $userBindVipPackage->bind_method_name;
                    $vip_package_time = date("Y-m-d H:i:s",$userBindVipPackage->created_at->timestamp);
                    $vip_package_end_time = $userBindVipPackage->end_time;

                    $data = [
                        'vip_package_id' => $vip_package_id,
                        'vip_package_name' => $vip_package_name,
                        'vip_package_free' => $vip_package_free,
                        'bind_method' => $bind_method,
                        'bind_method_name' => $bind_method_name,
                        'vip_package_time' => $vip_package_time,
                        'vip_package_end_time' => $vip_package_end_time
                    ];

                    array_push($vipPackageList,$data);
                }
            }

            $userInfo->vip_package_list = $vipPackageList;
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $userInfo]);
    }

    /**
     * vip用户列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getVipUserList(Request $request){
        $page          = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit         = !is_null($request->get('limit'))? $request->get('limit'): 10;
        $keyword       = !is_null($request->get('keyword')) ? $request->get('keyword') : '';
        $isMemberUnit  = !is_null($request->get('is_member_unit')) ? $request->get('is_member_unit') : '';

        $pageInfo=[
            'page'  =>$page,
            'limit' =>$limit
        ];

        $dataUserIds = [];
        $userWhetherVipOne = VipInfo::whereStatus(1)->where('end_time','>',date('Y-m-d H:i:s',time()))->get();
        if(count($userWhetherVipOne) > 0){
            foreach($userWhetherVipOne as $val){
                array_push($dataUserIds,$val->user_id);
            }
        }

        $vipUnitIds = UnitBindVipPackage::where('end_time','>',date('Y-m-d H:i:s',time()))->pluck('unit_id')->toArray();

        $vipUnitUserIds = UserXUnit::whereIn('unit_id',$vipUnitIds)->pluck('user_id');

        /** @var UnitAuth $item */
        $userWhetherVipTwo = UnitAuth::whereIn('user_id',$vipUnitUserIds)->whereIsAuth(1)->get();
        if(count($userWhetherVipTwo) > 0){
            foreach($userWhetherVipTwo as $item){
                array_push($dataUserIds,$item->user_id);
            }
        }

        array_unique($dataUserIds);

        /** @var User $user */
        $users = User::whereIn('id',$dataUserIds)->whereRole(0);

        if($keyword != ''){
            $nickname   =UserInfo::where('nickname','like','%'.trim($keyword).'%')->orWhere('realname','like','%'.trim($keyword).'%')->pluck('user_id')->toArray();

            $users->whereIn('id',$nickname)->orWhere('phone','like','%'.trim($keyword).'%');
        }

        if($isMemberUnit !== ''){
            $unitIds = Units::whereIsMemberUnit($isMemberUnit)->pluck('id');

            $userXUnitIds = UserXUnit::whereIn('unit_id',$unitIds)->pluck('user_id');

            $users = $users->whereIn('id',$userXUnitIds);
        }

        $pageInfo['total'] = $users->count();

        $users = $users->orderBy('created_at','desc')->offset(($page - 1) * $limit)->limit($limit)->get();
        if(count($users) > 0){
            foreach($users as $user){
                $user->userInfo;
                if ($user->userInfo){
                    $userInfo = CommonManager::getUserBasicInfo($user->id);
                    if($userInfo){
                        $user->userInfo->photo_url = $userInfo['photo_url'];
                        $user->userInfo->is_personal_auth = $userInfo['is_personal_auth'];
                        $user->userInfo->is_unit_auth = $userInfo['is_unit_auth'];
                        $user->userInfo->is_expert_auth = $userInfo['is_expert_auth'];
                        $user->userInfo->is_member_unit = $userInfo['is_member_unit'];
                        $user->userInfo->is_vip = $userInfo['is_vip'];
                        $user->userInfo->vip_package_name = '';
                        $user->userInfo->vip_package_time = '';
                        $user->userInfo->vip_package_end_time = '';

                        $userBindVipPackageList = CommonManager::getUserBindVipPackageInfo($user->id);
                        if(count($userBindVipPackageList) > 0){
                            foreach($userBindVipPackageList as $userBindVipPackage){
                                if(!empty($userBindVipPackage->vip_package_info)){
                                    $user->userInfo->vip_package_name = $userBindVipPackage->vip_package_info->name;
                                }

                                $user->userInfo->vip_package_time = date("Y-m-d H:i:s",$userBindVipPackage->created_at->timestamp);
                                $user->userInfo->vip_package_end_time = $userBindVipPackage->end_time;

                                break;
                            }
                        }
                    }
                }
            }
        }

        return response()->json(['level'=>'success','message'=>'success','data'=>$users,'page_info'=>$pageInfo]);

    }

    /**
     * 获取专家库
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getExpertsList(Request $request){
        $limit         = !is_null($request->get('limit')) ? $request->get('limit') : 8;
        $page          = !is_null($request->get('page')) ? $request->get('page') : 1;
        $keyword       = !is_null($request->get('keyword')) ? $request->get('keyword') : '';
        $isAuth        = !is_null($request->get('is_auth')) ? $request->get('is_auth') : '';

        $pageInfo = [
            'limit' => $limit,
            'page' => $page,
        ];

        $page = $page - 1;
        $expertList = CommonManager::getExpertInfoList('backstage','list',$keyword,$limit,$page,$isAuth);
        $pageInfo['total'] = CommonManager::getExpertInfoDNum($keyword,$isAuth);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $expertList,'page_info' => $pageInfo]);
    }

    /**
     * 获取专家库详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getExpertDetail(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $expert = CommonManager::getExpertInfoList('backstage','detail','',0,0,'',$id);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $expert]);
    }

    /**
     * 设置专家
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setExpert(Request $request){
        $userId              = !is_null($request->get('user_id')) ? $request->get('user_id') : 0;
        $realname            = !is_null($request->get('realname')) ? $request->get('realname') : '';
        $photoId             = !is_null($request->get('photo_id')) ? $request->get('photo_id') : 0;
        $unitName            = !is_null($request->get('unit_name')) ? $request->get('unit_name') : '';
        $position            = !is_null($request->get('position')) ? $request->get('position') : '';
        $phone               = !is_null($request->get('phone')) ? $request->get('phone') : '';
        $province            = !is_null($request->get('province')) ? $request->get('province') : '';
        $city                = !is_null($request->get('city')) ? $request->get('city') : '';
        $area                = !is_null($request->get('area')) ? $request->get('area') : '';
        $strengths           = !is_null($request->get('strengths')) ? $request->get('strengths') : '';
        $labels              = $request->get('labels');
        $qualificationImgs   = $request->get('qualification_imgs');
        $id                  = !is_null($request->get('id')) ? $request->get('id') : 0;
        $status              = !is_null($request->get('status')) && $request->get('status') != '' ? $request->get('status') : 1;
        $sort                = !is_null($request->get('sort')) ? $request->get('sort') : 0;

        if(!in_array($status,[1,3]))
            return response()->json(['level' => 'error','message' => '认证状态错误']);


        $expert = Experts::whereId($id)->first();
        if (!$expert) {
            $user_id = 0;
            $user = User::whereId($userId)->first();
            if ($user){
                $userInfo = UserInfo::whereUserId($user->id)->first();
                if(!$userInfo)
                    return response()->json(['level' => 'error', 'message' => '用户信息不存在']);

                $user_id = $user->id;
            }else{
                $user_id = 4;
            }



            $expert = new Experts();
            $expert->user_id  = $user_id;
            $expert->is_auth  = 1;
        }

        if($realname != ''){
            $expert->realname                 = $realname;
            if(!empty($userInfo)){
                $userInfo->realname       = $realname;
                $userInfo->save();
            }else{
                $userInfo = UserInfo::whereUserId($expert->user_id)->first();
                if($userInfo){
                    $userInfo->realname       = $realname;
                    $userInfo->save();
                }
            }
        }
        if($photoId != 0)$expert->photo_id                    = $photoId;
        if($unitName != '')$expert->unit_name                 = $unitName;
        if($position != '')$expert->position                  = $position;
        if($phone != '')$expert->phone                        = $phone;
        if($province != '')$expert->province                  = $province;
        if($city != '')$expert->city                          = $city;
        if($area != '')$expert->area                          = $area;
        if($strengths != '')$expert->strengths                = $strengths;
        if($expert)$expert->is_auth                           = $status;
        $expert->sort                                         = $sort;
        $expert->save();

        if (is_array($labels) && count($labels) > 0){
            $expertLabelList = ExpertLabel::whereExpertId($expert->id)->get();
            if(count($expertLabelList) > 0){
                foreach ($expertLabelList as $expertLabel) {
                    $expertLabel->forceDelete();
                }
            }

            foreach ($labels as $label) {
                $newExpertLabel = new ExpertLabel();
                $newExpertLabel->expert_id = $expert->id;
                $newExpertLabel->name = $label;
                $newExpertLabel->save();
            }
        }

        if(is_array($qualificationImgs) && count($qualificationImgs) > 0){
            $expertQualificationImgList = ExpertQualificationImg::whereExpertId($expert->id)->get();
            if(count($expertQualificationImgList) > 0){
                foreach ($expertQualificationImgList as $expertQualificationImg) {
                    $expertQualificationImg->forceDelete();
                }
            }

            foreach($qualificationImgs as $qualificationImg){
                $newQualificationImgs = new ExpertQualificationImg();
                $newQualificationImgs->expert_id        = $expert->id;
                $newQualificationImgs->img_id           = $qualificationImg;
                $newQualificationImgs->save();
            }
        }

        return response()->json(['level' => 'success','message' => '设置成功','data' => $expert]);
    }

    /**
     * 删除专家
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delExpert(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var Experts $expert */
        $expert = Experts::whereId($id)->whereIn('is_auth',[1,3])->first();
        if(!$expert)
            return response()->json(['level' => 'error','message' => '专家不存在']);

        Comment::whereExpertId($expert->id)->delete();

        $expert->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $expert]);
    }

    /**
     * 获取专家的官方点评列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getExpertOfficialCommentList(Request $request){
        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page  = !is_null($request->get('page')) ? $request->get('page') : 1;
        $id    = !is_null($request->get('id')) ? $request->get('id') : 0;

        $pageInfo = [
            'limit' => $limit,
            'page' => $page,
        ];

        $page = $page - 1;
        $expertOfficialCommentList = CommonManager::getCommentList($id,'expert',$limit,$page);
        $pageInfo['total'] = CommonManager::getCommentNum($id,'expert');

        return response()->json(['level' => 'success','message' => '获取成功','data' => $expertOfficialCommentList,'page_info' => $pageInfo]);
    }

    /**
     * 获取专家的官方点评详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getExpertOfficialCommentDetail(Request $request){
        $id    = !is_null($request->get('id')) ? $request->get('id') : 0;

        $expertOfficialCommentList = CommonManager::getCommentDetail($id,'expert');

        return response()->json(['level' => 'success','message' => '湖区成功','data' => $expertOfficialCommentList]);
    }

    /**
     * 设置专家的官方点评
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setExpertOfficialComment(Request $request){
        $id        = !is_null($request->get('id')) ? $request->get('id') : 0;
        $expertId  = !is_null($request->get('expert_id')) ? $request->get('expert_id') : 0;
        $content   = !is_null($request->get('content')) ? $request->get('content') : '';

        $expert = Experts::whereId($expertId)->first();
        if(!$expert)
            return response()->json(['level' => 'error','message' => '专家不存在']);

        $expertOfficialComment = Comment::whereId($id)->whereIsOfficial(1)->whereStatus(1)->whereType('expert')->first();
        if(!$expertOfficialComment)
            $expertOfficialComment = new Comment();

        $expertOfficialComment->expert_id                     = $expertId;
        $expertOfficialComment->type                          = 'expert';
        if($content != '')$expertOfficialComment->content     = $content;
        $expertOfficialComment->is_official                   = 1;
        $expertOfficialComment->status                        = 1;
        $expertOfficialComment->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $expertOfficialComment]);
    }

    /**
     * 删除专家的官方点评
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delExpertOfficialComment(Request $request){
        $id      = !is_null($request->get('id')) ? $request->get('id') : 0;

        $expertOfficialComment = Comment::whereId($id)->whereIsOfficial(1)->whereStatus(1)->whereType('expert')->first();
        if(!$expertOfficialComment)
            return response()->json(['level' => 'error','message' => '数据不存在']);

        $expertOfficialComment->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $expertOfficialComment]);
    }

    /**
     * 获取用户协议
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserAgreement(Request $request){
        $userAgreement = SysSetUp::whereType(0)->orderBy('created_at','desc')->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $userAgreement]);
    }

    /**
     * 发布用户协议
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setUserAgreement(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $content = !is_null($request->get('content')) ? $request->get('content') : '';

        if($content == '')
            return response()->json(['level' => 'error','message' => '请填写协议内容']);

        $newSysSetUp = SysSetUp::whereType(0)->orderBy('created_at','desc')->first();
        if(!$newSysSetUp)
            $newSysSetUp = new SysSetUp();

        $newSysSetUp->content       = $content;
        $newSysSetUp->type          = 0;
        $newSysSetUp->status        = 1;
        $newSysSetUp->save();

        return response()->json(['level' => 'success','message' => '发布成功','data' => $newSysSetUp]);
    }

    /**
     * 改变协议状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeAgreementStatus(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        /** @var SysSetUp $newSysSetUp */
        $newSysSetUp = SysSetUp::whereType(0)->orderBy('created_at','desc')->first();
        if(!$newSysSetUp)
            return response()->json(['level' => 'error','message' => '请先发布用户协议']);

        if($newSysSetUp->status == 0){
            $newSysSetUp->status = 1;
        }else{
            $newSysSetUp->status = 0;
        }

        $newSysSetUp->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newSysSetUp]);
    }

    /**
     * 获取认证规则和权益
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAuthenticateRule(Request $request){
        $userAgreement = SysSetUp::whereType(1)->orderBy('created_at','desc')->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $userAgreement]);
    }

    /**
     * 发布认证规则及权益
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setAuthenticateRule(Request $request){
        /** @var User $adminUser */
        $adminUser = UserManager::isLogin($request,$front = 1);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $content = !is_null($request->get('content')) ? $request->get('content') : '';

        if($content == '')
            return response()->json(['level' => 'error','message' => '请填写认证规则']);

        $newSysSetUp = SysSetUp::whereType(1)->orderBy('created_at','desc')->first();
        if(!$newSysSetUp)
            $newSysSetUp = new SysSetUp();

        $newSysSetUp->content       = $content;
        $newSysSetUp->type          = 1;
        $newSysSetUp->status        = 1;
        $newSysSetUp->save();

        return response()->json(['level' => 'success','message' => '发布成功','data' => $newSysSetUp]);
    }

    /**
     * 组列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGroupList(Request $request){
        $limit = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page  = !is_null($request->get('page')) ? $request->get('page') : 1;

        $pageInfo = [
            'limit' =>  $limit,
            'page' => $page
        ];

        /** @var Group $group */
        $groupList = Group::whereNull('deleted_at');

        $pageInfo['total'] = $groupList->count();

        $groupList = $groupList->orderBy('sort','asc')->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($groupList) > 0){
            foreach($groupList as $group){
                $group->group_member_num = GroupXUser::whereGroupId($group->id)->count();
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $groupList,'page_info' => $pageInfo]);
    }

    /**
     * 组详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGroupDetail(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $group = Group::whereId($id)->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $group]);
    }

    /**
     * 设置组
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setGroup(Request $request){
        $name   = !is_null($request->get('name')) ? $request->get('name') : '';
        $remark = !is_null($request->get('remark')) ? $request->get('remark') : '';
        $sort   = !is_null($request->get('sort')) ? $request->get('sort') : 0;
        $id     = !is_null($request->get('id')) ? $request->get('id') : 0;

        $newGroup = Group::whereId($id)->first();
        if(!$newGroup)
            $newGroup = new Group();

        $newGroup->name      = $name;
        $newGroup->remark    = $remark;
        $newGroup->sort      = $sort;
        $newGroup->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newGroup]);
    }

    /**
     * 删除组
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delGroup(Request $request){
        $id     = !is_null($request->get('id')) ? $request->get('id') : 0;

        $newGroup = Group::whereId($id)->first();
        if(!$newGroup)
            return response()->json(['level' => 'error','message' => '删除失败']);

        $groupMemberList = GroupXUser::whereGroupId($newGroup->id)->get();
        if(count($groupMemberList) > 0){
            foreach($groupMemberList as $groupMember){
                $groupMember->delete();
            }
        }

        $newGroup->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $newGroup]);
    }

    /**
     * 获取未加入该组的用户列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getNotJoinGroupUserList(Request $request){
        $page            = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit           = !is_null($request->get('limit'))? $request->get('limit'): 10;
        $keyword         = !is_null($request->get('keyword')) ? $request->get('keyword') : '';
        $groupId         = !is_null($request->get('group_id'))? $request->get('group_id'): 10;

        $pageInfo=[
            'page'     =>$page,
            'limit'    =>$limit,
            'keyword'  => $keyword,
            'group_id' => $groupId
        ];

        $groupMemberUserIds = GroupXUser::whereGroupId($groupId)->pluck('user_id');

        $users = User::whereRole(0)->whereNotIn('id',$groupMemberUserIds);

        if ($keyword != ''){
            $nickname   =UserInfo::where('nickname','like','%'.trim($keyword).'%')->orWhere('realname','like','%'.trim($keyword).'%')->pluck('user_id')->toArray();
            $users->whereIn('id',$nickname)->orWhere('phone','like','%'.trim($keyword).'%');
        }

        $pageInfo['total'] = $users->count();

        $users = $users->orderBy('created_at','desc')->offset(($page - 1) * $limit)->limit($limit)->get();
        if (count($users) > 0){
            /** @var User $user */
            foreach ($users as $user){
                $user->userInfo;
                if ($user->userInfo){
                    $user->userInfo->photo_url = '';
                    $user->userInfo->is_personal_auth = 0;
                    $user->userInfo->is_unit_auth = 0;
                    $user->userInfo->work_img_url = '';
                    $user->userInfo->is_expert_auth = 0;
                    $user->userInfo->is_member_unit = 0;
                    $user->userInfo->is_vip = 0;

                    $user->userInfo->vip_package_name = '';

                    $userBindVipPackageList = CommonManager::getUserBindVipPackageInfo($user->id);
                    if(count($userBindVipPackageList) > 0){
                        foreach($userBindVipPackageList as $userBindVipPackage){
                            if(!empty($userBindVipPackage->vip_package_info)){
                                $user->userInfo->vip_package_name = $userBindVipPackage->vip_package_info->name;
                            }
                            break;
                        }
                    }

                    $userInfo = CommonManager::getUserBasicInfo($user->id);
                    if($userInfo){
                        $user->userInfo->photo_url = $userInfo['photo_url'];
                        $user->userInfo->is_personal_auth = $userInfo['is_personal_auth'];
                        $user->userInfo->is_unit_auth = $userInfo['is_unit_auth'];
                        if($userInfo['is_personal_auth'] == 1){
                            $personalAuth = PersonalAuth::whereUserId($user->id)->whereIsAuth(1)->first();
                            if($personalAuth){
                                $user->userInfo->work_img_url = FileManager::getImgUrl($personalAuth->work_img_id);
                            }
                        }
                        $user->userInfo->is_expert_auth = $userInfo['is_expert_auth'];
                        $user->userInfo->is_member_unit = $userInfo['is_member_unit'];
                        $user->userInfo->is_vip = $userInfo['is_vip'];
                    }
                }
            }
        }

        return response()->json(['level'=>'success','message'=>'success','data'=>$users,'page_info'=>$pageInfo]);
    }

    /**
     * 获取组员列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGroupMemberList(Request $request){
        $limit   = !is_null($request->get('limit')) ? $request->get('limit') : 10;
        $page    = !is_null($request->get('page')) ? $request->get('page') : 1;
        $groupId = !is_null($request->get('group_id')) ? $request->get('group_id') : 0;

        $pageInfo = [
            'limit' =>  $limit,
            'page' => $page,
            'group_id' => $groupId
        ];

        /** @var GroupXUser $groupMember */
        $groupMemberList = GroupXUser::whereGroupId($groupId);

        $pageInfo['total'] = $groupMemberList->count();

        $groupMemberList = $groupMemberList->orderBy('sort','desc')->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        if(count($groupMemberList) > 0){
            foreach ($groupMemberList as $groupMember) {
                $groupMember->realname = '';
                $groupMember->phone    = '';

                $userBasicInfo = CommonManager::getUserBasicInfo($groupMember->user_id);
                if($userBasicInfo){
                    $groupMember->realname = $userBasicInfo['realname'] ? $userBasicInfo['realname'] : $userBasicInfo['nickname'] ? $userBasicInfo['nickname'] : '';
                    $groupMember->phone    = $userBasicInfo['phone'];
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $groupMemberList,'page_info' => $pageInfo]);
    }

    /**
     * 获取组员详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGroupMemberDetail(Request $request){
        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $groupMember = GroupXUser::whereId($id)->first();
        if($groupMember){
            $groupMember->realname = '';
            $groupMember->phone    = '';

            $userBasicInfo = CommonManager::getUserBasicInfo($groupMember->user_id);
            if($userBasicInfo){
                $groupMember->realname = $userBasicInfo['realname'] ? $userBasicInfo['realname'] : $userBasicInfo['nickname'] ? $userBasicInfo['nickname'] : '';
                $groupMember->phone    = $userBasicInfo['phone'];
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $groupMember]);
    }

    /**
     * 添加组员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setGroupMember(Request $request){
        $groupId  = !is_null($request->get('group_id')) ? $request->get('group_id') : 0;
        $userIds  = !is_null($request->get('user_id')) ? $request->get('user_id') : 0;

        if(!is_array($userIds) || (is_array($userIds) && count($userIds) <= 0))
            return response()->json(['level' => 'error','message' => '请选择用户']);

        $group = Group::whereId($groupId)->first();
        if(!$group)
            return response()->json(['level' => 'error','message' => '组不存在']);

        foreach($userIds as $userId){
            $groupXUser = GroupXUser::whereGroupId($group->id)->whereUserId($userId)->first();
            if(!$groupXUser){
                $newGroupXUser = new GroupXUser();
                $newGroupXUser->user_id        = $userId;
                $newGroupXUser->group_id       = $group->id;
                $newGroupXUser->save();
            }
        }

        return response()->json(['level' =>  'success','message' => '添加成功','data' => $newGroupXUser]);
    }

    /**
     * 删除组员
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function delGroupMember(Request $request){
        $id      = !is_null($request->get('id')) ? $request->get('id') : 0;

        $groupMember = GroupXUser::whereId($id)->first();
        if(!$groupMember)
            return response()->json(['level' => 'error','message' => '删除失败']);

        $groupMember->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $groupMember]);
    }
}
